<template>
  <div class="dashboard-container">
    <!-- 时间选择器 -->
    <el-card shadow="hover" class="mb-20">
      <div class="date-picker-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="refreshData">查询</el-button>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 基础文本统计 -->
      <el-col :span="24" class="mb-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>基础文本统计</span>
            </div>
          </template>
          <div class="stats-container">
            <div class="stat-item">
              <div class="stat-label">总提问次数</div>
              <div class="stat-value">{{ basicTextStats.messageCount || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">平均提问长度</div>
              <div class="stat-value">{{ (basicTextStats.averageLength || 0).toFixed(2) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 提问主题分析 -->
      <el-col :span="12" class="mb-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>提问主题分布</span>
            </div>
          </template>
          <div ref="topicChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 高频词分析 -->
      <el-col :span="12" class="mb-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>提问高频词</span>
            </div>
          </template>
          <div ref="wordChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 提问用户Top -->
      <el-col :span="24" class="mb-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>提问用户Top</span>
            </div>
          </template>
          <div ref="userChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import req from '@/request';

// 获取本月第一天和最后一天
const getCurrentMonthRange = () => {
  const now = new Date();
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  
  // 格式化日期为 yyyy-MM-dd
  const format = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  return [format(firstDay), format(lastDay)];
};

// 日期范围
const dateRange = ref(getCurrentMonthRange())
const visitDate = ref({
  startDate: dateRange.value[0],
  endDate: dateRange.value[1]
})

// 数据
const basicTextStats = ref({})
const analyzeQuestionTopics = ref({})
const frequentWords = ref([])
const topAskingUsers = ref([])

// 图表DOM引用
const topicChart = ref(null)
const wordChart = ref(null)
const userChart = ref(null)

// 处理日期变化
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    visitDate.value = {
      startDate: val[0],
      endDate: val[1]
    }
  }
}

// 刷新数据
const refreshData = () => {
  if (!visitDate.value.startDate || !visitDate.value.endDate) {
    ElMessage.warning('请选择开始和结束日期')
    return
  }
  
  // 重置图表
  if (topicChart.value) {
    echarts.getInstanceByDom(topicChart.value)?.dispose()
  }
  if (wordChart.value) {
    echarts.getInstanceByDom(wordChart.value)?.dispose()
  }
  if (userChart.value) {
    echarts.getInstanceByDom(userChart.value)?.dispose()
  }
  
  // 重新获取数据
  initData()
}

// 获取基础文本统计
const fetchBasicTextStats = async () => {
  try {
    const response = await req.post('/conversationLogs/basicTextStats', visitDate.value)
    if (response.code === 200) {
      basicTextStats.value = response.data
    } else {
      ElMessage.error(response.message || '获取基础文本统计失败')
    }
  } catch (error) {
    console.error('获取基础文本统计出错:', error)
    ElMessage.error('请求出错: ' + (error.message || '未知错误'))
  }
}

// 获取提问主题分析
const fetchAnalyzeQuestionTopics = async () => {
  try {
    const response = await req.post('/conversationLogs/analyzeQuestionTopics', visitDate.value)
    if (response.code === 200) {
      analyzeQuestionTopics.value = response.data
      initTopicChart()
    } else {
      ElMessage.error(response.message || '获取提问主题分析失败')
    }
  } catch (error) {
    console.error('获取提问主题分析出错:', error)
    ElMessage.error('请求出错: ' + (error.message || '未知错误'))
  }
}

// 获取高频词
const fetchFrequentWords = async () => {
  try {
    const response = await req.post('/conversationLogs/frequentWords', visitDate.value)
    if (response.code === 200) {
      frequentWords.value = response.data
      initWordChart()
    } else {
      ElMessage.error(response.message || '获取高频词失败')
    }
  } catch (error) {
    console.error('获取高频词出错:', error)
    ElMessage.error('请求出错: ' + (error.message || '未知错误'))
  }
}

// 获取提问用户Top
const fetchTopAskingUsers = async () => {
  try {
    const response = await req.post('/conversationLogs/topAskingUsers', visitDate.value)
    if (response.code === 200) {
      topAskingUsers.value = response.data
      initUserChart()
    } else {
      ElMessage.error(response.message || '获取提问用户Top失败')
    }
  } catch (error) {
    console.error('获取提问用户Top出错:', error)
    ElMessage.error('请求出错: ' + (error.message || '未知错误'))
  }
}

// 初始化主题分析图表（折线图）
const initTopicChart = () => {
  if (!topicChart.value) return
  
  const chart = echarts.init(topicChart.value)
  const topics = Object.keys(analyzeQuestionTopics.value)
  const counts = Object.values(analyzeQuestionTopics.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}次'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: topics,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '提问次数'
    },
    series: [
      {
        name: '提问次数',
        type: 'line',
        data: counts,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化高频词图表（横向柱状图）
const initWordChart = () => {
  if (!wordChart.value) return
  
  const chart = echarts.init(wordChart.value)
  
  // 处理数据，按词频排序
  const wordsData = frequentWords.value
    .map(item => {
      const key = Object.keys(item)[0]
      return { name: key, value: item[key] }
    })
    .sort((a, b) => b.value - a.value)
    .slice(0, 10) // 取前10个高频词
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}次'
    },
    grid: {
      left: '3%',
      right: '65px',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '出现次数'
    },
    yAxis: {
      type: 'category',
      data: wordsData.map(item => item.name),
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: '出现次数',
        type: 'bar',
        data: wordsData.map(item => item.value),
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
              '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'
            ]
            return colorList[params.dataIndex]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}次'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化用户Top图表（柱状图）
const initUserChart = () => {
  if (!userChart.value) return
  
  const chart = echarts.init(userChart.value)
  
  // 处理数据
  const usersData = topAskingUsers.value.map(item => ({
    name: item.username,
    value: item.messagesCount
  }))
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}次'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: usersData.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '提问次数'
    },
    series: [
      {
        name: '提问次数',
        type: 'bar',
        data: usersData.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化所有数据
const initData = () => {
  fetchBasicTextStats()
  fetchAnalyzeQuestionTopics()
  fetchFrequentWords()
  fetchTopAskingUsers()
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.stats-container {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 0 20px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.date-picker-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>